package com.dhh.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;

import com.dhh.R;
import com.dhh.dao.DataBaseHelper;
import com.dhh.util.Constant;
import com.dhh.util.StringUtil;
import com.dhh.util.manager.FoodLogManager;
import com.dhh.util.manager.PlanManager;
import com.dhh.vo.FoodLog;
import com.dhh.vo.FoodPlan;
import com.dhh.vo.PlanItem;
import com.dhh.widget.AmazingAdapter;
import com.dhh.widget.AmazingListView;

import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem;
import greendroid.widget.NormalActionBarItem;

public class FoodLogActivity extends GDActivity{	
	private DataBaseHelper db;
	private PlanManager pManager;
	private FoodLogManager flManager;
	private FoodPlan plan;
	private Map<String,List<FoodLog>> foodMap;
	private AmazingListView lsComposer;
	private String date;
	
	@Override
    public void onCreate(Bundle intent){
		 super.onCreate(intent);
	        requestWindowFeature(Window.FEATURE_NO_TITLE);
	        setActionBarContentView(R.layout.food_log);
	        
	        db = new DataBaseHelper(getBaseContext());
	        db.openDataBase();
	        pManager = new PlanManager(db); 	
	        flManager = new FoodLogManager(db);
	        
	        date = getIntent().getExtras().getString(Constant.C_LOG_DATE);
	        initActionBar();
	        initView();
	}
	
	@Override
	public void onStart() {
        super.onStart();
		fillData();		
    }
	
	@Override
    public void onResume(){
    	super.onResume();
        db.openDataBase();       
    }
    
    @Override
	protected void onPause(){
		super.onPause();
		if (db != null) {
			db.close();
		}
	}
    
    @Override
	protected void onStop(){
		super.onStop();
	}
	
	private void initActionBar(){
		getActionBar().setTitle("Today's Log");
        getActionBar().setBackgroundColor(Color.rgb(14, 166, 249));
        addActionBarItem(getActionBar()
                .newActionBarItem(NormalActionBarItem.class)
                .setDrawable(android.R.drawable.ic_input_add), R.id.action_bar_home_add);
	}
	
	public boolean onHandleActionBarItemClick(ActionBarItem item, int i) {
		if(item.getItemId() == R.id.action_bar_home_add){
			Intent intent = new Intent(FoodLogActivity.this,FoodAddActivity.class);
			intent.putExtra("activity", Constant.ACTIVITY_FOOD_LOG);
			startActivity(intent);			
		}
		return true;
	}
	
	private void initView(){
		lsComposer = (AmazingListView) findViewById(R.id.lsComposer);
		lsComposer.setDivider( null );
		lsComposer.setDividerHeight(1); 
		lsComposer.setPinnedHeaderView(LayoutInflater.from(this).inflate(R.layout.fp_items, lsComposer, false));
		lsComposer.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {				
//				cItemId = ((TextView) view.findViewById(R.id.fp_item_id)).getText().toString();
//				DietDesignActivity.this.showDialog(0);
				
				return true;
			}
		});
	}
	
	private void fillData(){
		foodMap = flManager.getLog(date);
		plan = pManager.getCurrentPlan();
		plan.initCurentCount();
		lsComposer.setAdapter(new SectionComposerAdapter());
		
		((TextView)findViewById(R.id.mp_plan_grain_t)).setText(plan.getGrain());
		((TextView)findViewById(R.id.mp_plan_grain_u)).setText(plan.getGrainUnit());
		((TextView)findViewById(R.id.mp_plan_grain_c)).setText(plan.getCurrentGrain());
		
		((TextView)findViewById(R.id.mp_plan_fruit_t)).setText(plan.getFruit());
		((TextView)findViewById(R.id.mp_plan_fruit_u)).setText(plan.getFruitUnit());
		((TextView)findViewById(R.id.mp_plan_fruit_c)).setText(plan.getCurrentFruit());
		
		((TextView)findViewById(R.id.mp_plan_vegetable_t)).setText(plan.getVegetable());
		((TextView)findViewById(R.id.mp_plan_vegetable_u)).setText(plan.getVegetableUnit());
		((TextView)findViewById(R.id.mp_plan_vegetable_c)).setText(plan.getCurrentVegetable());
		
		((TextView)findViewById(R.id.mp_plan_dairy_t)).setText(plan.getDairy());
		((TextView)findViewById(R.id.mp_plan_dairy_u)).setText(plan.getDairyUnit());
		((TextView)findViewById(R.id.mp_plan_dairy_c)).setText(plan.getCurrentDairy());
		
		((TextView)findViewById(R.id.mp_plan_protein_t)).setText(plan.getProteinFood());
		((TextView)findViewById(R.id.mp_plan_protein_u)).setText(plan.getProteinFoodUnit());
		((TextView)findViewById(R.id.mp_plan_protein_c)).setText(plan.getCurrentProteinFood());
		
		((TextView)findViewById(R.id.mp_plan_energy_t)).setText(plan.getEnergy());
		((TextView)findViewById(R.id.mp_plan_energy_c)).setText(plan.getCurrentEnergy());
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Pair<String, List<FoodLog>>>  getAllData(){
		List<Pair<String, List<FoodLog>>>  lst = new ArrayList<Pair<String, List<FoodLog>>>();
		Pair bPair = new Pair(PlanItem.PERIOD_BREAKFAST,foodMap.get(PlanItem.PERIOD_BREAKFAST));
		Pair lPair = new Pair(PlanItem.PERIOD_LUNCH,foodMap.get(PlanItem.PERIOD_LUNCH));
		Pair dPair = new Pair(PlanItem.PERIOD_DINNER,foodMap.get(PlanItem.PERIOD_DINNER));
		Pair daPair = new Pair(PlanItem.PERIOD_SNACK,foodMap.get(PlanItem.PERIOD_SNACK));
		lst.add(bPair);
		lst.add(lPair);
		lst.add(dPair);
		lst.add(daPair);
		return lst;
	}
	
	class SectionComposerAdapter extends AmazingAdapter {
		List<Pair<String, List<FoodLog>>> all = getAllData();

		@Override
		public int getCount() {
			int res = 0;
			for (int i = 0; i < all.size(); i++) {
				res += all.get(i).second.size();
			}
			return res;
		}

		@Override
		public FoodLog getItem(int position) {
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (position >= c && position < c + all.get(i).second.size()) {
					return all.get(i).second.get(position - c);
				}
				c += all.get(i).second.size();
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		protected void onNextPageRequested(int page) {
		}

		@Override
		protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
			if (displaySectionHeader) {
				view.findViewById(R.id.header).setVisibility(View.VISIBLE);
				TextView lSectionTitle = (TextView) view.findViewById(R.id.header);
				lSectionTitle.setText(getSections()[getSectionForPosition(position)]);
			} else {
				view.findViewById(R.id.header).setVisibility(View.GONE);
			}
		}

		@Override
		public View getAmazingView(int position, View convertView, ViewGroup parent) {
			View res = convertView;
			if (res == null) res = getLayoutInflater().inflate(R.layout.item_composer, null);
			TextView foodName = (TextView) res.findViewById(R.id.fp_foodname);
			TextView foodGroup = (TextView) res.findViewById(R.id.fp_foodgroup);
			TextView service = (TextView) res.findViewById(R.id.fp_service);
			TextView calorie = (TextView) res.findViewById(R.id.fp_calorie);
			TextView itemId = (TextView) res.findViewById(R.id.fp_item_id);
			
			FoodLog log = getItem(position);
			foodName.setText(StringUtil.cutString(log.getFoodName(),40));
			foodGroup.setText(log.getFoodGroup()+",");
			service.setText(log.getServing()+",");
			calorie.setText(log.getEnergy()+" cal");
			itemId.setText(log.getId());
			
			return res;
		}

		@Override
		public void configurePinnedHeader(View header, int position, int alpha) {
			TextView lSectionHeader = (TextView)header;
			lSectionHeader.setText(getSections()[getSectionForPosition(position)]);
			lSectionHeader.setBackgroundColor(alpha << 24 | (0xbbffbb));
			lSectionHeader.setTextColor(alpha << 24 | (0x000000));
		}

		@Override
		public int getPositionForSection(int section) {
			if (section < 0) section = 0;
			if (section >= all.size()) section = all.size() - 1;
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (section == i) { 
					return c;
				}
				c += all.get(i).second.size();
			}
			return 0;
		}

		@Override
		public int getSectionForPosition(int position) {
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (position >= c && position < c + all.get(i).second.size()) {
					return i;
				}
				c += all.get(i).second.size();
			}
			return -1;
		}

		@Override
		public String[] getSections() {
			String[] res = new String[all.size()];
			for (int i = 0; i < all.size(); i++) {
				res[i] = all.get(i).first;
			}
			return res;
		}
		
	}
}
